/*
 * Copyright 2009 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.kommando.core.selector;

import java.awt.event.ActionEvent;
import java.util.Collections;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JPopupMenu;

import org.kommando.core.KommandoWindow;
import org.kommando.core.action.Action;
import org.kommando.core.action.ActionRepository;
import org.kommando.core.catalog.CatalogObject;
import org.kommando.core.search.ActionSearcher;
import org.kommando.core.search.Result;

/**
 * 
 * 
 * @author Peter De Bruycker
 */
public class ActionSelector extends AbstractSelector<Action> {

    private ActionRepository actionRepository;
    private CatalogObject directObject;
    private ActionSearcher actionSearcher = new ActionSearcher();

    public ActionSelector(CommandSelector commandSelector, ActionRepository actionRepository) {
        super(commandSelector, KommandoWindow.Selector.ACTION);
        this.actionRepository = actionRepository;
    }

    /**
     * @see org.kommando.core.selector.AbstractSelector#doSearch(java.util.List, java.lang.String)
     */
    @Override
    protected List<Result<Action>> doSearch(List<Action> candidates, String query) {
        if (directObject == null) {
            return Collections.emptyList();
        }

        return actionSearcher.searchActions(candidates, directObject, query);
    }

    public void setDirectObject(CatalogObject directObject) {
        this.directObject = directObject;
        this.queryChanged("");
    }

    public Action getAction() {
        return getInternalSelection();
    }

    /**
     * @see org.kommando.core.selector.AbstractSelector#getInitialState()
     */
    @Override
    protected SelectorState<Action> getInitialState() {
        return new SelectorState<Action>(actionRepository.getActions());
    }

    @Override
    protected JPopupMenu createPopupMenu(final Action action) {
        JPopupMenu popupMenu = new JPopupMenu();

        popupMenu.add(new AbstractAction("Debug info") {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(action);
            }
        });

        return popupMenu;
    }
}
